package com.ktjiaoyu.ktmall.servlet.api;

import com.alibaba.fastjson.JSON;
import com.ktjiaoyu.ktmall.entity.Product;
import com.ktjiaoyu.ktmall.service.ProductService;
import com.ktjiaoyu.ktmall.service.impl.ProductServiceImpl;
import com.ktjiaoyu.ktmall.utils.R;
import com.ktjiaoyu.ktmall.utils.RequestUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "ProductServlet", urlPatterns = "/api/product/*")
public class ProductServlet extends HttpServlet {
    protected final ProductService productService = new ProductServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        String path = request.getPathInfo();
        PrintWriter out = response.getWriter();
        R result;

        try {
            if (path == null || "/list".equals(path)) {
                String title = request.getParameter("title");
                Long categoryId = RequestUtil.parseLong(request, "categoryId", null);
                int page = RequestUtil.parseInt(request, "page", 1);
                int pageSize = RequestUtil.parseInt(request, "pageSize", 10);
                List<Product> list = productService.findList(title, categoryId, page, pageSize);
                int total = productService.count(title, categoryId);
                Map<String, Object> data = new HashMap<>();
                data.put("list", list);
                data.put("total", total);
                result = R.ok(data);
            } else if (path.matches("/\\d+")) {
                Long id = Long.valueOf(path.substring(1));
                Product product = productService.findById(id);
                result = product != null ? R.ok(product) : R.fail("商品不存在");
            } else {
                result = R.fail("无效的请求路径");
            }
        } catch (Exception e) {
            result = R.fail("服务器处理错误: " + e.getMessage());
            e.printStackTrace();
        }

        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        try (BufferedReader reader = request.getReader()) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            Product product = JSON.parseObject(sb.toString(), Product.class);
            boolean success;
            if (product.getId() == null) {
                success = productService.insert(product) > 0;
            } else {
                success = productService.update(product) > 0;
            }
            R result = success ? R.ok() : R.fail("保存失败");
            PrintWriter out = response.getWriter();
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
        } catch (Exception e) {
            R result = R.fail("服务器处理错误: " + e.getMessage());
            PrintWriter out = response.getWriter();
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
            e.printStackTrace();
        }
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        String path = request.getPathInfo();
        PrintWriter out = response.getWriter();
        try {
            if (path != null && path.matches("/\\d+")) {
                Long id = Long.valueOf(path.substring(1));
                boolean success = productService.removeById(id);
                R result = success ? R.ok() : R.fail("删除失败");
                out.print(JSON.toJSONString(result));
            } else {
                out.print(JSON.toJSONString(R.fail("无效的请求路径")));
            }
        } catch (Exception e) {
            out.print(JSON.toJSONString(R.fail("服务器处理错误: " + e.getMessage())));
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        String path = request.getPathInfo();
        PrintWriter out = response.getWriter();
        try {
            if (path != null && path.matches("/\\d+/status")) {
                // 1. 解析商品ID（修复可能的数组越界风险）
                String[] pathParts = path.split("/");
                if (pathParts.length < 3) {
                    out.print(JSON.toJSONString(R.fail("无效的状态更新路径")));
                    return;
                }
                Long id = Long.valueOf(pathParts[1]);

                // 2. 读取并解析请求体
                try (BufferedReader reader = request.getReader()) {
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                    Map<String, Object> map = JSON.parseObject(sb.toString(), Map.class);

                    // 3. 安全获取并转换status（核心修复点）
                    Object statusObj = map.get("status");
                    Integer status = null;
                    if (statusObj != null) {
                        if (statusObj instanceof Integer) {
                            // 如果本身是Integer类型，直接赋值
                            status = (Integer) statusObj;
                        } else if (statusObj instanceof String) {
                            // 如果是String类型，尝试转换为Integer
                            try {
                                status = Integer.parseInt((String) statusObj);
                            } catch (NumberFormatException e) {
                                out.print(JSON.toJSONString(R.fail("status必须是有效的数字")));
                                return;
                            }
                        } else {
                            // 其他类型（如Double），先转为String再转换
                            status = Integer.parseInt(statusObj.toString());
                        }
                    }

                    // 4. 验证status不为空
                    if (status == null) {
                        out.print(JSON.toJSONString(R.fail("status参数不能为空")));
                        return;
                    }

                    // 5. 调用服务更新状态
                    boolean success = productService.updateStatus(id, status);
                    R result = success ? R.ok() : R.fail("更新状态失败");
                    out.print(JSON.toJSONString(result));
                }
            } else {
                out.print(JSON.toJSONString(R.fail("无效的请求路径")));
            }
        } catch (NumberFormatException e) {
            // 捕获ID或status转换为数字的异常
            out.print(JSON.toJSONString(R.fail("参数格式错误：ID或status必须是数字")));
            e.printStackTrace();
        } catch (Exception e) {
            // 捕获其他未知异常
            out.print(JSON.toJSONString(R.fail("服务器处理错误: " + e.getMessage())));
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
    }
}
